package dataStructureAlgorithms;

/**
 * @Description: TODO 数组实现的栈
 * @Author: wzj
 * @Date: 2019/10/8 7:27
 */
public class ArrayStack {
    private int[] stack;

    public ArrayStack(){
        stack=new int[0];
    }

    /**
     * 入栈
     * @param value
     */
    public void push(int value){
        int[] stackNew=new int[stack.length+1];
        for(int i=0;i<stackNew.length-1;i++){
            stackNew[i]=stack[i];
        }
        stackNew[stack.length]=value;
        stack=stackNew;
    }

    /**
     * 出栈
     */
    public void pop(){
        if(stack.length==0){
            throw new RuntimeException("栈空");
        }
        int[] stackNew=new int[stack.length-1];
        for(int i=0;i<stackNew.length;i++){
            stackNew[i]=stack[i];
        }
        stack=stackNew;
    }

    /**
     * 查看栈顶元素
     * @return
     */
    public int peek(){
        if(stack.length==0){
            throw new RuntimeException("栈空");
        }
        return stack[stack.length-1];
    }

    /**
     * 栈是否为空
     * @return
     */
    public boolean isEmpty(){
        return stack.length==0;
    }

    public static void main(String[] args) {
        ArrayStack arrayStack=new ArrayStack();
        arrayStack.push(5);
        System.out.println(arrayStack.peek());
        arrayStack.push(4);
        System.out.println(arrayStack.peek());
        arrayStack.push(3);
        System.out.println(arrayStack.peek());
        arrayStack.push(2);
        System.out.println(arrayStack.peek());
        arrayStack.pop();
        System.out.println(arrayStack.peek());
        arrayStack.pop();
        System.out.println(arrayStack.peek());

    }
}
